import { create } from "zustand";

export interface Components {
    id: number;
    name: string;
    props: any; // 组件的属性
    description: string; // 组件的描述
    children?: Components[]; // 子组件
    parentId?: number; // 父组件的id
}

export interface State {
    compoents: Components[];
}

export interface Action {
    addComponent: (compoent: any, parentId?: number) => void;
    deleteComponent: (componentId: number) => void;
    updateComponent: (componentId: number, newProps: any) => void;
}
// 返回一个函数体，函数体返回一个对象，对象包含数据和方法
export const useComponentsStore = create<State & Action>((set, get) => ({
    //数据
    // mode: 'edit',
    compoents: [
        {
            id: 1,
            name: 'Page',
            props: {},
            description: '页面',
        }
    ],
    //方法
    // setMode: () => set((state: any) => ({ mode: state.mode == 'edit' ? 'preview' : 'edit' }))

    // 本质上就是要将一个对象添加到另一个对象当中
    addComponent: (compoent: any, parentId?: number) => {
        set((state) => {
            if (parentId) {
                // 找到父组件
                const parent = getComponentById(parentId, state.compoents);
                if (parent) {
                    parent.children ? parent.children.push(compoent) : parent.children = [compoent];
                }
                return { compoents: [...state.compoents] }
            }
            return { compoents: [...state.compoents, compoent] }
        })

    },
    // 在整个 json 对象中找到某一个子对象的id，移除该对象
    deleteComponent: (id: number) => {
        if (!id) return { compoents: [...get().compoents] }
        const component = getComponentById(id, get().compoents);
        if (component?.parentId) {
            const parentComponent = getComponentById(component.parentId, get().compoents);
            if (parentComponent) {
                parentComponent.children = parentComponent.children?.filter((item) => item.id !== id);
            }
            set({ compoents: [...get().compoents] })
        }
    },
    updateComponent: (componentId: number, props: any) => {
        set((state) => {
            const component = getComponentById(componentId, state.compoents);
            if (component) {
                component.props = { ...component.props, ...props };
                return { compoents: [...state.compoents] }
            }
            return { compoents: [...state.compoents] }
        })
    },

}))

// export default useComponentsStore


export function getComponentById(id: number | null, compoent: Components[]): Components | null {
    if (!id) return null;
    for (const item of compoent) {
        if (item.id == id) {
            return item;
        }
        if (item.children && item.children.length > 0) {
            const result = getComponentById(id, item.children);
            if (result) return result;
        }
    }
    return null;
}